package top.sxlai.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hbase.io.ByteArrayOutputStream;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.sql.rowset.serial.SerialBlob;
import java.io.InputStream;
import java.sql.Blob;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.Base64;
import java.util.HashSet;
import java.util.Set;

/**
 * @author : sxl
 * @date : 2024/3/31 10:42
 * @Version: 1.0
 */
@Component
@Slf4j
public class HandFileUtil {
    //锁
    private static final Object lock = new Object();
    //文件类型的处理
    private static final Set<String> VIDEO_EXTENSIONS = new HashSet<>(Arrays.asList("mp4", "avi", "mov", "mkv"));
    private static final Set<String> AUDIO_EXTENSIONS = new HashSet<>(Arrays.asList("mp3", "wav", "ogg", "aac"));
    private static final Set<String> IMAGE_EXTENSIONS = new HashSet<>(Arrays.asList("jpg", "jpeg", "png", "gif"));
    private static final Set<String> DOCUMENT_EXTENSIONS = new HashSet<>(Arrays.asList("doc", "docx", "pdf", "txt"));
    // 添加其他类型文件后缀名，例如压缩文件、表格文件等
    private static final Set<String> OTHER_EXTENSIONS = new HashSet<>(Arrays.asList("zip", "rar", "xls", "xlsx"));
    /**
     * 配置文件类型
     * @param file 文件
     * @return 文件类型
     */
    @Autowired
    private FileSystem fileSystem;

    public static String handFileToLocal(MultipartFile file) {
        //获取文件类型后缀名
        String originalFilename = file.getOriginalFilename();
        // 获取最后一个"."出现的位置，即文件后缀名的起始位置
        int dotIndex = originalFilename.lastIndexOf(".");
        String fileType = originalFilename.substring(dotIndex + 1);

        //文件类型 typeId
        String typeId;
        //处理文件类型
        if (VIDEO_EXTENSIONS.contains(fileType)) {
            //视频类型，typeId设置为 2
            typeId = "2";
            return typeId;
        } else if (AUDIO_EXTENSIONS.contains(fileType)) {
            //音频类型，typeId设置为 3
            typeId = "3";
            return typeId;
        } else if (IMAGE_EXTENSIONS.contains(fileType)) {
            //图片类型，typeId设置为 4
            typeId = "4";
            return typeId;
        } else if (DOCUMENT_EXTENSIONS.contains(fileType)) {
            //文件类型，typeId设置为 5
            typeId = "5";
            return typeId;
        } else {
            //其他类型，typeId设置为 6
            typeId = "6";
            return typeId;
        }
        //将元数据存储到数据库
    }

    // 将文件转换为base64编码
    public String getFileBase64(String filePath) throws Exception {
        Path path = new Path(filePath);
        try (
                //  FileSystem fs = FileSystem.get(conf);
                InputStream inputStream = fileSystem.open(path);
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) > 0) {
                outputStream.write(buffer, 0, bytesRead);
            }
            byte[] fileBytes = outputStream.toByteArray();
            String fileExtension = getFileExtension(filePath);
            if (IMAGE_EXTENSIONS.contains(fileExtension)) {
                return "data:image/" + fileExtension + ";base64," + Base64.getEncoder().encodeToString(fileBytes);
            } else if (VIDEO_EXTENSIONS.contains(fileExtension)) {
                return "data:video/" + fileExtension + ";base64," + Base64.getEncoder().encodeToString(fileBytes);
            } else if (AUDIO_EXTENSIONS.contains(fileExtension)) {
                return "data:audio/" + fileExtension + ";base64," + Base64.getEncoder().encodeToString(fileBytes);
            } else if (DOCUMENT_EXTENSIONS.contains(fileExtension)) {
                return "data:application/" + fileExtension + ";base64," + Base64.getEncoder().encodeToString(fileBytes);
            } else if (OTHER_EXTENSIONS.contains(fileExtension)) {
                return base64ToBlob(Base64.getEncoder().encodeToString(fileBytes)).toString();
            } else {
                return "Unknown file type";
            }
        }
    }

    // 获取文件扩展名
    private String getFileExtension(String filePath) {
        int dotIndex = filePath.lastIndexOf('.');
        if (dotIndex == -1) {
            return "";
        }
        return filePath.substring(dotIndex + 1).toLowerCase();
    }
    // 将base64编码的数据转换为Blob对象
    public Blob base64ToBlob(String base64Data) throws SQLException {
        String[] parts = base64Data.split(",");
        if (parts.length == 2) {
            String header = parts[0];
            String base64String = parts[1];

            // 提取MIME类型
            String mimeType = header.substring(header.indexOf(':') + 1, header.indexOf(';'));

            // 解码base64数据
            byte[] decodedBytes = Base64.getDecoder().decode(base64String);

            // 创建Blob对象
            return new SerialBlob(decodedBytes);
        }
        return null;
    }
}
